package com.acane.instagram.feature.login

import android.util.Log
import androidx.lifecycle.ViewModel
import com.acane.instagram.core.config.WebSocketManager
import com.acane.instagram.core.model.UserInfo
import com.acane.instagram.core.model.network.datasource.MyRetrofitDatasource
import com.acane.instagram.feature.common.SessionManager
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow

class LoginViewModel(
    //private val context: Context
) : ViewModel() {
    private val _loginState = MutableStateFlow<LoginState>(LoginState.Idle)
    val loginState: StateFlow<LoginState> = _loginState

//    init {
//        // 初始化Retrofit数据源
//        MyRetrofitDatasource.init(context)
//        // 初始化SessionManager
//        SessionManager.init(context)
//    }

    suspend fun login(
        username: String?,
        password: String?,
        toMain: () -> Unit = {},
        toFriend: (() -> Unit)? = null
    ) : UserInfo? {
        _loginState.value = LoginState.Loading
        val response = MyRetrofitDatasource.login(username, password)
        try {
            Log.d("LoginViewModel", "刚进入登录${response}")
            if (response.code != 200) {
                _loginState.value = LoginState.Error(response.msg)
                return null
            } else {
                _loginState.value = LoginState.Success
                SessionManager.login(response.data.user, response.data.sessionId)
                Log.d("LoginViewModel", "login success: ${response}")
                toMain()
            }

//            // 存储JWT
//            SessionManager.init(context)
//            SessionManager.login(response.data.user, response.data.sessionId,
//                response.data.token
//            )
            if (toFriend != null) {
                Log.d("LoginViewModel", "此次为从聊天页面登录直接跳转toFriend")
                // 登录成功后
                WebSocketManager.connect(SessionManager._sessionId!!)
                toFriend()
            } else {
                Log.d("LoginViewModel", "toFriend为空")
                // 登录成功后
                WebSocketManager.connect(SessionManager._sessionId!!)
                toMain()
            }
        } catch (e: Exception) {
            _loginState.value = LoginState.Error(e.message ?: "网络错误")
        }
        return response.data.user
    }

    sealed class LoginState {
        object Idle : LoginState()
        object Loading : LoginState()
        object Success : LoginState()
        data class Error(val message: String) : LoginState()
    }
}
